/**
 *
 */
package com.itee.core.serial;

import gnu.io.CommPortIdentifier;
import java.nio.charset.Charset;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.serial.SerialAddress;
import org.apache.mina.transport.serial.SerialConnector;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;

/**
 * 串口工具类
 *
 * @author xin
 */
public class SerialUtils {

    private IoConnector connector;

    /**
     *
     */
    public SerialUtils(IoHandler handler,ProtocolCodecFactory factory) {
        connector = new SerialConnector();
        connector.setHandler(handler);

        //connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(factory));
        //connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.getFilterChain().addLast( "logger", new LoggingFilter() );
        connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter( factory));
        //connector.getSessionConfig().setReadBufferSize( 2048 );
    }

    public IoSession connect(SerialParam param) {
        SerialAddress portAddress = new SerialAddress(param.getName(), param.getBauds(), param.getDataBits(),
                param.getStopBits(), param.getParity(), param.getFlowControl());
        ConnectFuture future = connector.connect(portAddress);
        future.awaitUninterruptibly();

        return future.getSession();
    }

    public void dispose() {
        connector.dispose();
    }

    /**
     * 列举本机所有可用串口
     *
     * @return
     */
    public static String[] listPortChoics() {
        List<String> ports = new ArrayList<>();
        for (Enumeration<?> en = CommPortIdentifier.getPortIdentifiers(); en.hasMoreElements(); ) {
            CommPortIdentifier portId = (CommPortIdentifier) en.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                ports.add(portId.getName());
            }
        }
        return ports.toArray(new String[ports.size()]);
    }
}
